package com.lapelittle.framework.service;

import com.lapelittle.framework.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;

@Service
public class EmailService {
    @Autowired
    private JavaMailSender mailSender;
    
    @Value("${spring.mail.username}")
    private String from;
    
    // 验证码过期时间（分钟）
    private static final int CODE_EXPIRE_MINUTES = 5;
    
    // 验证码长度
    private static final int CODE_LENGTH = 6;
    
    // 使用ConcurrentHashMap存储验证码和过期时间
    private static final Map<String, EmailCode> CODE_MAP = new ConcurrentHashMap<>();
    
    /**
     * 发送验证码
     */
    public void sendCode(String email) {
        // 生成验证码
        String code = generateCode();
        
        // 发送邮件
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(email);
        message.setSubject("验证码");
        message.setText("您的验证码是：" + code + "，" + CODE_EXPIRE_MINUTES + "分钟内有效。");
        
        try {
            mailSender.send(message);
            // 保存验证码和过期时间
            long expireTime = System.currentTimeMillis() + CODE_EXPIRE_MINUTES * 60 * 1000;
            CODE_MAP.put(email, new EmailCode(code, expireTime));
        } catch (Exception e) {
            throw new BusinessException("验证码发送失败");
        }
    }
    
    /**
     * 验证验证码
     */
    public boolean verifyCode(String email, String code) {
        EmailCode emailCode = CODE_MAP.get(email);
        
        if (emailCode == null) {
            throw new BusinessException("验证码不存在");
        }
        
        if (System.currentTimeMillis() > emailCode.getExpireTime()) {
            CODE_MAP.remove(email);
            throw new BusinessException("验证码已过期");
        }
        
        if (!emailCode.getCode().equals(code)) {
            throw new BusinessException("验证码错误");
        }
        
        // 验证成功后删除验证码
        CODE_MAP.remove(email);
        return true;
    }
    
    /**
     * 生成验证码
     */
    private String generateCode() {
        Random random = new Random();
        StringBuilder code = new StringBuilder();
        for (int i = 0; i < CODE_LENGTH; i++) {
            code.append(random.nextInt(10));
        }
        return code.toString();
    }
    
    /**
     * 验证码对象，包含验证码和过期时间
     */
    private static class EmailCode {
        private final String code;
        private final long expireTime;
        
        public EmailCode(String code, long expireTime) {
            this.code = code;
            this.expireTime = expireTime;
        }
        
        public String getCode() {
            return code;
        }
        
        public long getExpireTime() {
            return expireTime;
        }
    }
    
    /**
     * 清理过期的验证码
     * @return 清理的数量
     */
    public int cleanExpiredCodes() {
        int count = 0;
        long now = System.currentTimeMillis();
        for (Map.Entry<String, EmailCode> entry : CODE_MAP.entrySet()) {
            if (now > entry.getValue().getExpireTime()) {
                CODE_MAP.remove(entry.getKey());
                count++;
            }
        }
        return count;
    }
} 